// @flow
import React, { Component } from 'react'
import styles from './VarComp.css'
import { Modal, message } from 'antd'
import VarModalContent from './VarModalContent'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import VarGrid from './VarGrid'

type Props = {
  location: Object,
  pointData: Array<Object>,
  varData: Array<Object>,
  refreshVar: Function,
  refreshLimit: Function
}
type States = {
  visibleVariable: boolean,
  confirmLoading: boolean,
  variableType: Array<Object>
}
class VarComp extends Component {
  props: Props
  state: States
  showVarModal: Function
  handleVariableOk: Function
  handleVariableCancel: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      visibleVariable: false,
      confirmLoading: false,
      variableType: []
    }
    this.showVarModal = this.showVarModal.bind(this)
    this.handleVariableOk = this.handleVariableOk.bind(this)
    this.handleVariableCancel = this.handleVariableCancel.bind(this)
  }
  handleVariableOk () {
    const varForm = this.refs.varModal.getForm()
    varForm.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        confirmLoading: true
      })
      const values = {
        ...fieldsValue,
        variableName: fieldsValue.kmxVariableName,
        variableNameEn: fieldsValue.kmxVariableNameEn,
        variableType: fieldsValue.kmxVariableType,
        unit: fieldsValue.kmxUnit
      }
      universalFetch(`${__SERVICE_API__}device/monitors/variables`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('变量添加成功')
        this.props.refreshVar()
        this.setState({
          visibleVariable: false,
          confirmLoading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          confirmLoading: false
        })
        message.error('变量添加失败: ' + error.message, 10)
      })
    })
  }
  showVarModal () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=variableType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          variableType: json.result.variableType,
          visibleVariable: true
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  handleVariableCancel () {
    this.setState({
      visibleVariable: false
    })
  }
  render () {
    const { pointData, varData, refreshVar, refreshLimit } = this.props
    const { variableType } = this.state
    return (
      <div className={styles['main']}>
        {
          // <Button type='primary' style={{ marginLeft: '10px' }}
          // onClick={() => this.showVarModal()}>添加变量</Button>
        }
        <div className={styles['title']}
          >变量：</div>
        <VarGrid {...{
          refreshVar,
          getVarLimits: refreshLimit,
          rowData: varData
        }} />
        <Modal
          title='添加变量'
          visible={this.state.visibleVariable}
          onOk={this.handleVariableOk}
          confirmLoading={this.state.confirmLoading}
          onCancel={this.handleVariableCancel}
          >
          <VarModalContent ref='varModal' {...{
            pointData: pointData,
            variableType
          }
           } />
        </Modal>
      </div>
    )
  }
}

export default VarComp
